﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.IO;

namespace Aj.Core
{

    /// <summary>
    /// 普通页面的基类
    /// </summary>
    public abstract class PageBase : System.Web.UI.Page
    {
        private ScriptDictionary _scriptBlocks;

        public ScriptDictionary ScriptBlocks
        {
            get
            {
                return _scriptBlocks;
            }
        }
        protected override void Render(HtmlTextWriter writer)
        {
            if (Function.GetLimit())
            {
                if (ScriptBlocks != null)
                {
                    StringWriter sw = new StringWriter();
                    HtmlTextWriter htmlWriter = new HtmlTextWriter(sw);
                    base.Render(htmlWriter);
                    string html = sw.ToString();
                    int startPoint = html.IndexOf("<head>", StringComparison.OrdinalIgnoreCase);
                    if (startPoint == -1)
                        startPoint = html.IndexOf("<body>", StringComparison.OrdinalIgnoreCase);
                    html = html.Insert(startPoint > 0 ? startPoint + 6 : 0, ScriptBlocks.ToString());
                    writer.Write(html);
                }
                else
                {
                    base.Render(writer);
                }
            }
            else
            {
                writer.Write("<center>网站维护中...</center>");
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
        }
        #region [ 判断是Get/Post ]
        public bool IsGet
        {
            get
            {
                return HttpContext.Current.Request.HttpMethod.Equals("GET");
            }
        }

        public bool IsPost
        {
            get
            {
                return HttpContext.Current.Request.HttpMethod.Equals("POST");
            }
        }
        #endregion

        #region 得到页面的QueryString/Form参数值，并安全地转换为指定的类型
        /// <summary>
        /// 读取QueryString参数值为字符串
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public virtual string QueryParam(string name)
        {
            return QueryParam(name, String.Empty);
        }
        /// <summary>
        /// 读取QueryString参数值为字符串
        /// </summary>
        /// <param name="name"></param>
        /// <param name="defValue"></param>
        /// <returns></returns>
        public virtual string QueryParam(string name, string defValue)
        {
            string sParam = GetQueryValue(name);
            return sParam ?? defValue;
        }
        /// <summary>
        /// 读取QueryString参数值为Guid字符串
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public virtual string QueryParamGuid(string name)
        {
            return QueryParamGuid(name, String.Empty);
        }
        /// <summary>
        /// 读取QueryString参数值为Guid字符串
        /// </summary>
        /// <param name="name"></param>
        /// <param name="defaultVal"></param>
        /// <returns></returns>
        public virtual string QueryParamGuid(string name, string defaultVal)
        {
            try
            {
                return new Guid(QueryParam(name)).ToString();
            }
            catch
            {
                return string.Empty;
            }
        }
        /// <summary>
        /// 读取QueryString参数值16位整数
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public virtual int QueryParamInt16(string name)
        {
            return QueryParamInt16(name, 0);
        }
        /// <summary>
        /// 读取QueryString参数值16位整数
        /// </summary>
        /// <param name="name"></param>
        /// <param name="defValue"></param>
        /// <returns></returns>
        public virtual int QueryParamInt16(string name, short defValue)
        {
            return Function.SafeInt16(QueryParam(name), defValue);
        }
        /// <summary>
        /// 读取QueryString参数值32位整数
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public virtual int QueryParamInt32(string name)
        {
            return QueryParamInt32(name, 0);
        }
        /// <summary>
        /// 读取QueryString参数值32位整数
        /// </summary>
        /// <param name="name"></param>
        /// <param name="defValue"></param>
        /// <returns></returns>
        public virtual int QueryParamInt32(string name, int defValue)
        {
            return Function.SafeInt32(QueryParam(name), defValue);
        }

        public long QueryParamInt64(string name)
        {
            return QueryParamInt64(name, 0);
        }

        public long QueryParamInt64(string name, int defValue)
        {
            return Function.SafeInt64(QueryParam(name), defValue);
        }

        /// <summary>
        /// 读取QueryString参数值为double浮点数
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public virtual double QueryParamFloat(string name)
        {
            return QueryParamFloat(name, 0d);
        }
        /// <summary>
        /// 读取QueryString参数值为double浮点数
        /// </summary>
        /// <param name="name"></param>
        /// <param name="defValue"></param>
        /// <returns></returns>
        public virtual double QueryParamFloat(string name, double defValue)
        {
            return Function.SafeFloat(QueryParam(name), defValue);
        }
        /// <summary>
        /// 读取Form参数值为字符串
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public virtual string FormParam(string name)
        {
            return FormParam(name, String.Empty);
        }
        /// <summary>
        /// 读取Form参数值为字符串
        /// </summary>
        /// <param name="name"></param>
        /// <param name="defValue"></param>
        /// <returns></returns>
        public virtual string FormParam(string name, string defValue)
        {
            string sParam = GetFormValue(name);
            return sParam ?? defValue;
        }

        /// <summary>
        /// 读取Form参数值为Guid字符串
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public virtual string FormParamGuid(string name)
        {
            return FormParamGuid(name, String.Empty);
        }
        /// <summary>
        /// 读取Form参数值为Guid字符串
        /// </summary>
        /// <param name="name"></param>
        /// <param name="defaultVal"></param>
        /// <returns></returns>
        public virtual string FormParamGuid(string name, string defaultVal)
        {
            try
            {
                return new Guid(FormParam(name)).ToString();
            }
            catch
            {
                return string.Empty;
            }
        }
        /// <summary>
        /// 读取Form参数值16位整数
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public virtual int FormParamInt16(string name)
        {
            return FormParamInt16(name, 0);
        }
        /// <summary>
        /// 读取Form参数值16位整数
        /// </summary>
        /// <param name="name"></param>
        /// <param name="defValue"></param>
        /// <returns></returns>
        public virtual int FormParamInt16(string name, short defValue)
        {
            return Function.SafeInt16(FormParam(name), defValue);
        }
        /// <summary>
        /// 读取Form参数值32位整数
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public virtual int FormParamInt32(string name)
        {
            return FormParamInt32(name, 0);
        }
        /// <summary>
        /// 读取Form参数值32位整数
        /// </summary>
        /// <param name="name"></param>
        /// <param name="defValue"></param>
        /// <returns></returns>
        public virtual int FormParamInt32(string name, int defValue)
        {
            return Function.SafeInt32(FormParam(name), defValue);
        }

        public long FormParamInt64(string name)
        {
            return FormParamInt64(name, 0);
        }

        public long FormParamInt64(string name, int defValue)
        {
            return Function.SafeInt64(FormParam(name), defValue);
        }

        /// <summary>
        /// 读取Form参数值为double浮点数
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public virtual double FormParamFloat(string name)
        {
            return FormParamFloat(name, 0d);
        }
        /// <summary>
        /// 读取Form参数值为double浮点数
        /// </summary>
        /// <param name="name"></param>
        /// <param name="defValue"></param>
        /// <returns></returns>
        public virtual double FormParamFloat(string name, double defValue)
        {
            return Function.SafeFloat(FormParam(name), defValue);
        }
        #endregion

        #region 客户端脚本函数
        /// <summary>
        /// 在客户端弹出消息框
        /// </summary>
        public virtual void MessageBox()
        {
            MessageBox("发生错误！");
        }
        /// <summary>
        /// 在客户端弹出消息框
        /// </summary>
        /// <param name="ex"></param>
        public virtual void MessageBox(Exception ex)
        {
            MessageBox(ex.Message);
        }

        /// <summary>
        /// 在客户端弹出消息框
        /// </summary>
        /// <param name="s_Message">消息框的文字内容</param>
        public virtual void MessageBox(string s_Message)
        {
            MessageBox(s_Message, false);
        }
        /// <summary>
        /// 在客户端弹出消息框并关闭窗口
        /// </summary>
        /// <param name="s_Message"></param>
        /// <param name="close"></param>
        public virtual void MessageBox(string s_Message, bool close)
        {

            string script;
            if (close)
            {
                //script = "\n<script type=\"text/javascript\">\n<!--\nwindow.alert(\"" + s_Message + "\");doCloseWin();\n//-->\n</script>\n";
                script = "window.alert(\"" + s_Message + "\");doCloseWin();";
            }
            else
            {
                //script = "\n<script type=\"text/javascript\">\n<!--\nwindow.alert(\"" + s_Message + "\");\n//-->\n</script>\n"
                script = "window.alert(\"" + s_Message + "\");";
            }

            if (Form == null)
            {
                RegisterClientScriptBlock(typeof(PageBase), "MessageBox", script);
            }
            else
            {
                ClientScript.RegisterStartupScript(typeof(PageBase), "MessageBox", script, true);
            }
        }

        /// <summary>
        /// 在客户端弹出消息框，等用户确定后重定向到其他页面
        /// </summary>
        /// <param name="s_Message">消息框的文字内容</param>
        /// <param name="url">重定向的页面url</param>
        public virtual void MessageBoxGo(string s_Message, string url)
        {
            //string script = "\n<script type=\"text/javascript\">\n<!--\nalert(\"" + s_Message + "\");location.href=\"" + url + "\";\n//-->\n</script>\n"
            string script = "alert(\"" + s_Message + "\");location.href=\"" + url + "\";";

            if (Form == null)
            {
                RegisterClientScriptBlock(typeof(PageBase), "MessageBox", script);
            }
            else
            {
                ClientScript.RegisterStartupScript(typeof(PageBase), "MessageBox", script, true);
            }
        }
        /// <summary>
        /// 在客户端弹出消息框，等用户确定后重定向到其他页面
        /// </summary>
        /// <param name="s_Message">消息框的文字内容</param>
        /// <param name="rawurl"></param>
        public virtual void MessageBoxGo(string s_Message, bool rawurl)
        {
            if (rawurl)
            {
                this.MessageBoxGo(s_Message, HttpContext.Current.Request.Url.ToString());
            }
            else
            {
                this.MessageBoxGo(s_Message, HttpContext.Current.Request.Url.AbsolutePath.ToString());
            }
        }
        /// <summary>
        /// 在客户端弹出消息框，等用户确定后返回上一页
        /// </summary>
        /// <param name="s_Message"></param>
        public virtual void MessageBack(string s_Message)
        {
            //string script = "\n<script type=\"text/javascript\">\n<!--\nalert(\"" + s_Message + "\");history.back();\n//-->\n</script>\n";
            string script = "alert(\"" + s_Message + "\");history.back();";

            if (Form == null)
            {
                RegisterClientScriptBlock(typeof(PageBase), "MessageBox", script);
            }
            else
            {
                ClientScript.RegisterStartupScript(typeof(PageBase), "MessageBox", script, true);
            }
        }
        /// <summary>
        /// 将客户端重定向到新的 URL
        /// </summary>
        /// <param name="Url"></param>
        public virtual void Page_GoTo(string Url)
        {
            this.Page_GoTo(Url, false);
        }
        /// <summary>
        /// 将客户端重定向到新的 URL
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="endResponse"></param>
        public virtual void Page_GoTo(string Url, bool endResponse)
        {
            HttpContext.Current.Response.Redirect(Url, endResponse);
        }

        public void RegisterClientScriptBlock(Type type, string key, string script)
        {
            if (_scriptBlocks == null)
            {
                _scriptBlocks = new ScriptDictionary();
            }
            var scriptKey = new ScriptKey(type, key);
            if (_scriptBlocks[scriptKey] == null)
            {
                _scriptBlocks.Add(scriptKey, script);
            }
        }
        #endregion

        #region 表单/Cookie/ip操作

        public bool SetCookie(string name, string value, bool httpOnly, string path, string domain, DateTime? expires)
        {
            //HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
            //if (cookie == null)
            //{
            //    cookie = new HttpCookie(strName);
            //}
            //cookie.Value = HttpUtility.UrlEncode(strValue, System.Text.Encoding.GetEncoding("gb2312"));
            ////cookie.Value = strValue;
            //cookie.Expires = DateTime.Now.AddDays(1);
            //cookie.Domain = ".ccement.com";
            //HttpContext.Current.Response.Cookies.Add(cookie);

            try
            {
                HttpCookie a = new HttpCookie(name);
                a.Value = value;
                a.HttpOnly = httpOnly;
                if (path.IsNotNullAndEmpty())
                {
                    a.Path = path;
                }
                if (domain.IsNotNullAndEmpty())
                {
                    a.Domain = domain;
                }
                if (expires != null)
                {
                    a.Expires = expires.Value;
                }
                HttpContext.Current.Response.Cookies.Add(a);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public string GetIPAddress()
        {
            string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (result.IsNotNullAndEmpty())
            {
                //可能有代理 
                if (result.IndexOf(".") == -1)
                {
                    //没有"."肯定是非IPv4格式 
                    result = null;
                }
                else
                {
                    if (result.IndexOf(",") != -1)
                    {
                        //有","估计多个代理。取第一个不是内网的IP。 
                        result = result.Replace(" ", "").Replace(",", "");
                        string[] temparyip = result.Split(',', ';');
                        foreach (string t in temparyip)
                        {
                            if (Function.IsIP(t)
                                && t.Substring(0, 3) != "10."
                                && t.Substring(0, 7) != "172.16."
                                && t.Substring(0, 7) != "192.168")
                            {
                                return t; //找到不是内网的地址 
                            }
                        }
                    }
                    else if (Function.IsIP(result))
                    {
                        //代理即是IP格式 
                        return result;
                    }
                    else
                    {
                        //代理中的内容 非IP，取IP 
                        result = null;
                    }
                }
            }
            if (result.IsNullOrEmpty())
                result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            if (result.IsNullOrEmpty())
                result = HttpContext.Current.Request.UserHostAddress;
            return result;
        }

        public string GetQueryValue(string name)
        {
            return HttpContext.Current.Request.QueryString[name];
        }

        public string GetFormValue(string name)
        {
            return HttpContext.Current.Request.Form[name];
        }

        #endregion
    }


}
